<script>
export default {
    data(){
        return {
            socketUrl:"",
            socketTask:null,
            is_open_socket:false,
            qrCodeSrc:"",  //二维码图片
            qrCodeSrcChange:false, //刷新二维码用
            /*  */
            qrFn:null,  //
            messageFn:null //
        };
    },
    methods:{
        /* s */
        initSocket(
            socketUrl = "",  //
            qrFN = ()=>{},
            fn = ()=>{}  //
        ){
            this.socketUrl = socketUrl;
            //
            this.qrFN = qrFN;
            this.messageFn = fn;
            //
            this.socketTask = null;
            this.socketTask = wx.connectSocket({
                url: `${this.socketUrl}`
            });
            //
            uni.showLoading({});
            //
            this.socketTask.onOpen(res=>{
                console.log('WebSocket连接已打开！readyState=' + this.socketTask.readyState);
                this.is_open_socket = true;
                //
                this.qrCodeSrc = qrFN();
                //console.log(this.qrCodeSrc);
                uni.hideLoading();
            });
            //
            this.socketTask.onMessage(res=>{
                console.log("后台推送的数据",res);
                let data = JSON.parse(res.data);
                //回调方法
                fn.call(this,data);
                //
            });
            //
            this.socketTask.onError(res=>{
                console.log(res);
                console.log('readyState=' + this.socketTask.readyState);
                uni.hideLoading();
                //this.initSocket();
            })
            this.socketTask.onClose(res=>{
                console.log(`WebSocket连接已关闭！readyState=${this.socketTask.readyState},err=${JSON.stringify(res)}`);
                if(this.is_open_socket){
                    this.initSocket(
                        this.socketUrl,
                        this.qrFN,
                        this.messageFn.bind(this)
                    );
                }
            })
        },
        // 关闭websocket【离开这个页面的时候执行关闭】
        closeSocket() {
            this.socketTask.close({
                success:res=>{
                    this.is_open_socket = false;
                    console.log("websocket关闭成功", res);
                },
                fail:err=>{
                    console.log("websocket关闭失败", err);
                }
            })
        },
        // 刷新付款二维码
        refreshPayQrcode(){
            this.qrCodeSrcChange = false;
            this.qrCodeSrc = `${this.qrFN()}?${Math.random()*100}`;
            //console.log(this.qrCodeSrc);
            this.qrCodeSrcChange = true;
        },
        /* e */
    }
}
</script>